#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Vulkan API Performance Analysis Tool
用于分析和对比 OpenHarmony 与 Android 平台的 Vulkan 性能数据
"""

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import sys
import os

# 支持中文显示
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def load_profiling_data(filepath):
    """加载性能分析数据"""
    try:
        df = pd.read_csv(filepath)
        print(f"✓ 成功加载: {filepath}")
        print(f"  - API数量: {len(df)}")
        print(f"  - 总调用次数: {df['Call Count'].sum()}")
        return df
    except Exception as e:
        print(f"✗ 加载失败: {filepath}")
        print(f"  错误: {e}")
        return None

def analyze_single_platform(df, platform_name):
    """分析单个平台的性能数据"""
    print(f"\n{'='*60}")
    print(f"{platform_name} 平台性能分析")
    print(f"{'='*60}")
    
    # 基本统计
    total_calls = df['Call Count'].sum()
    total_time = df['Total Time(μs)'].sum()
    avg_time_per_call = total_time / total_calls if total_calls > 0 else 0
    
    print(f"\n📊 总体统计:")
    print(f"  总API数量: {len(df)}")
    print(f"  总调用次数: {total_calls:,}")
    print(f"  总耗时: {total_time:,.2f} μs ({total_time/1000:.2f} ms)")
    print(f"  平均每次调用: {avg_time_per_call:.2f} μs")
    
    # Top 10 最耗时的API
    print(f"\n🔥 Top 10 最耗时API (按总时间):")
    top10_total = df.nlargest(10, 'Total Time(μs)')
    for idx, row in enumerate(top10_total.itertuples(), 1):
        percentage = (row._3 / total_time * 100) if total_time > 0 else 0
        print(f"  {idx:2d}. {row._1:40s} {row._3:12,.2f} μs ({percentage:5.1f}%)")
    
    # Top 10 平均耗时最长的API
    print(f"\n⏱️  Top 10 单次最慢API (按平均时间):")
    top10_avg = df.nlargest(10, 'Avg Time(μs)')
    for idx, row in enumerate(top10_avg.itertuples(), 1):
        print(f"  {idx:2d}. {row._1:40s} {row._6:12,.2f} μs (调用{row._2}次)")
    
    # Pipeline阶段分析
    pipeline_apis = df[df['API Name'].str.contains('Pipeline::', na=False)]
    if len(pipeline_apis) > 0:
        print(f"\n🔄 渲染管线阶段分析:")
        for row in pipeline_apis.itertuples():
            avg_per_frame = row._3 / row._2 if row._2 > 0 else 0
            print(f"  {row._1:30s} {avg_per_frame:10,.2f} μs/frame")
    
    return top10_total, top10_avg

def compare_platforms(df1, df2, name1="OpenHarmony", name2="Android"):
    """对比两个平台的性能数据"""
    print(f"\n{'='*60}")
    print(f"{name1} vs {name2} 性能对比")
    print(f"{'='*60}")
    
    # 合并数据
    merged = pd.merge(df1, df2, on='API Name', suffixes=(f'_{name1}', f'_{name2}'))
    
    if len(merged) == 0:
        print("⚠️  没有找到共同的API,无法对比")
        return None
    
    print(f"\n📋 共同API数量: {len(merged)}")
    
    # 计算性能比率
    merged['Avg_Ratio'] = merged[f'Avg Time(μs)_{name1}'] / merged[f'Avg Time(μs)_{name2}']
    merged['Total_Ratio'] = merged[f'Total Time(μs)_{name1}'] / merged[f'Total Time(μs)_{name2}']
    
    # 找出差异最大的API
    print(f"\n🚀 {name1} 比 {name2} 快的API (Top 5):")
    faster = merged.nsmallest(5, 'Avg_Ratio')
    for idx, row in enumerate(faster.itertuples(), 1):
        speedup = 1 / row.Avg_Ratio
        print(f"  {idx}. {row._1:40s} 快 {speedup:6.2f}x")
        print(f"     ({getattr(row, f'Avg Time(μs)_{name2}'):8.2f} μs -> {getattr(row, f'Avg Time(μs)_{name1}'):8.2f} μs)")
    
    print(f"\n🐌 {name1} 比 {name2} 慢的API (Top 5):")
    slower = merged.nlargest(5, 'Avg_Ratio')
    for idx, row in enumerate(slower.itertuples(), 1):
        slowdown = row.Avg_Ratio
        print(f"  {idx}. {row._1:40s} 慢 {slowdown:6.2f}x")
        print(f"     ({getattr(row, f'Avg Time(μs)_{name2}'):8.2f} μs -> {getattr(row, f'Avg Time(μs)_{name1}'):8.2f} μs)")
    
    # 整体性能比较
    total1 = df1['Total Time(μs)'].sum()
    total2 = df2['Total Time(μs)'].sum()
    ratio = total1 / total2 if total2 > 0 else 0
    
    print(f"\n📈 整体性能对比:")
    print(f"  {name1} 总耗时: {total1:,.2f} μs")
    print(f"  {name2} 总耗时: {total2:,.2f} μs")
    print(f"  性能比率: {ratio:.3f}x")
    if ratio < 1:
        print(f"  ✓ {name1} 整体快 {1/ratio:.2f}x")
    else:
        print(f"  ✗ {name1} 整体慢 {ratio:.2f}x")
    
    return merged

def plot_comparison(merged, name1="OpenHarmony", name2="Android", output_file="comparison.png"):
    """绘制对比图表"""
    if merged is None or len(merged) == 0:
        print("⚠️  无数据可绘制")
        return
    
    # 选择Top 15共同API
    merged_sorted = merged.nlargest(15, f'Avg Time(μs)_{name1}')
    
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8))
    
    # 图1: 平均耗时对比
    api_names = merged_sorted['API Name'].apply(lambda x: x[:35] + '...' if len(x) > 35 else x)
    x = np.arange(len(api_names))
    width = 0.35
    
    ax1.barh(x - width/2, merged_sorted[f'Avg Time(μs)_{name1}'], width, label=name1, alpha=0.8)
    ax1.barh(x + width/2, merged_sorted[f'Avg Time(μs)_{name2}'], width, label=name2, alpha=0.8)
    ax1.set_yticks(x)
    ax1.set_yticklabels(api_names, fontsize=8)
    ax1.set_xlabel('Average Time (μs)')
    ax1.set_title(f'Top 15 API Average Time Comparison\n{name1} vs {name2}')
    ax1.legend()
    ax1.grid(axis='x', alpha=0.3)
    
    # 图2: 性能比率
    ratios = merged_sorted['Avg_Ratio']
    colors = ['green' if r < 1 else 'red' for r in ratios]
    ax2.barh(api_names, ratios, color=colors, alpha=0.6)
    ax2.axvline(x=1.0, color='black', linestyle='--', linewidth=1)
    ax2.set_xlabel(f'Performance Ratio ({name1} / {name2})')
    ax2.set_title(f'Performance Ratio (< 1.0 means {name1} is faster)')
    ax2.grid(axis='x', alpha=0.3)
    
    plt.tight_layout()
    plt.savefig(output_file, dpi=150, bbox_inches='tight')
    print(f"\n✓ 图表已保存: {output_file}")

def main():
    """主函数"""
    print("\n" + "="*60)
    print("Vulkan API Performance Analysis Tool")
    print("="*60)
    
    # 检查命令行参数
    if len(sys.argv) < 2:
        print("\n使用方法:")
        print("  单平台分析:")
        print("    python analyze_performance.py <profiling.csv>")
        print("\n  双平台对比:")
        print("    python analyze_performance.py <oh_profiling.csv> <android_profiling.csv>")
        print("\n示例:")
        print("    python analyze_performance.py vulkan_profiling.csv")
        print("    python analyze_performance.py oh_profiling.csv android_profiling.csv")
        return
    
    # 单平台分析
    if len(sys.argv) == 2:
        filepath = sys.argv[1]
        df = load_profiling_data(filepath)
        if df is not None:
            analyze_single_platform(df, "Platform")
    
    # 双平台对比
    elif len(sys.argv) == 3:
        filepath1 = sys.argv[1]
        filepath2 = sys.argv[2]
        
        df1 = load_profiling_data(filepath1)
        df2 = load_profiling_data(filepath2)
        
        if df1 is not None and df2 is not None:
            name1 = os.path.splitext(os.path.basename(filepath1))[0]
            name2 = os.path.splitext(os.path.basename(filepath2))[0]
            
            analyze_single_platform(df1, name1)
            analyze_single_platform(df2, name2)
            
            merged = compare_platforms(df1, df2, name1, name2)
            if merged is not None:
                output_file = f"comparison_{name1}_vs_{name2}.png"
                plot_comparison(merged, name1, name2, output_file)
    
    print("\n" + "="*60)
    print("分析完成!")
    print("="*60 + "\n")

if __name__ == "__main__":
    main()
